package com.hmall.item.listen;

import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.item.service.IItemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class DeduceStockListener {

    private final IItemService iItemService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "trade.item.success.queue", durable = "true"),
            exchange = @Exchange(name = "tradeitem.direct"),
            key = "tradeitem.success"
    ))
    public void deduceStock(List<OrderDetailDTO> detailDTOS)
    {
        log.info("开始处理库存扣减消息: {}", detailDTOS);
        try {
            iItemService.deductStock(detailDTOS);
            log.info("库存扣减完成");
        } catch (Exception e) {
            log.error("库存扣减失败", e);
        }
    }
}
